<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" width="120">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="height:100px"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatDate(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next,total"
            :total="total"
            :page-size="q.size"

            @current-change="handleCurrentChange"
          />

        </el-row>
      </el-card>
      <el-dialog
        :visible.sync="showDialog"
        title="新增员工"
      >
        <addor-edit
          v-if="showDialog"
          @close="showDialog=false"
          @success="hSuccess"
        />
      </el-dialog>
      <el-dialog title="二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="qrcodeCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog :visible.sync="showDialogRole" title="分配角色">
        <assign-role v-if="showDialogRole" :cur-id="curId" @close="showDialogRole=false" @success="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import addorEdit from './empDialog'
import employeeEnum from '@/constant/employees'
import { delEmplotee, getEmployeeList } from '@/api/employees'
import { transZhkeyToExcel } from '@/utils'
import QRCode from 'qrcode'
const hireType = {}
employeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      q: {
        page: 1,
        size: 10
      },
      total: 10,
      showDialog: false,
      showCodeDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {

    hAssignRole(row) {
      this.curId = row.id
      this.showDialogRole = true
    },
    showCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          const canvas = this.$refs.qrcodeCanvas
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请上传头像')
      }
    },
    exportExcel() {
    // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(async excel => {
        await this.loadEmployeeList()
        const { tHeader, data } = transZhkeyToExcel(this.list)
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // console.log(list, 'listaaaaaaaaaaaaaaaaaaaa')
        // const data = this.formatJson(filterVal, list)
        // console.log(data, 'dataaaaaaaaaaaaaaaaa') // [[1,'三体','刘慈欣',100000,'2022-11-05'],[2,'西游记','吴承恩',100000,'1995-11-05']]
        // const data = [[1, '三体', '刘慈欣', 100000, '2022-11-05'], [2, '西游记', '吴承恩', 100000, '1995-11-05']]
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    formatDate(id) {
      return hireType[id] || '未知'
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadEmployeeList()
    },
    hSuccess() {
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployeeList()
      this.showDialog = false
    },
    async  hDel(id) {
      this.$confirm('确认删除改员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmplotee(id)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.list.length === 1) {
          this.q.page--
          if (this.q.page <= 0) {
            this.q.page = 1
          }
        }
        this.loadEmployeeList()
      }).catch((error) => {
        this.$message.error(error)
      })
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.q)
        console.log(res)
        if (res.code !== 10000) return
        this.total = res.data.total
        this.list = res.data.rows
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    }
  }
}
</script>
